<?php
namespace App\Jobs;

use Illuminate\Support\Facades\Mail;

class PushLogToEmailJob extends Job
{
    /**
     * @var 消息日志
     */
    protected $messageLogged;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($messageLogged)
    {
        $this->messageLogged = $messageLogged;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $to = env('LOG_PUSH_TO_EMAIL', "");
        if (!isEmail($to)) {
            return false;
        }

        if (!env('MAIL_USERNAME', '') || !env('MAIL_PASSWORD', '')) {
            return false;
        }

        $appName = env("APP_NAME", "Scarecrow Log Engine");
        $subject = $appName . "[" . strtoupper($this->messageLogged['level']) . "]: " . mb_substr($this->messageLogged['message'], 0, 20) . (mb_strlen($this->messageLogged['message']) > 20 ? "..." : "");
        $allLevel = env('LOG_PUSH_EMAIL_LEVEL', '');
        $allLevel && $allLevel = explode(',', $allLevel);
        if (!$allLevel) {
            $allLevel = ['error'];
        } else {
            array_walk($allLevel, function (&$item) {
                $item = strtolower($item);
            });
        }

        if (in_array(strtolower($this->messageLogged['level']), $allLevel)) {
            Mail::html($this->createFormData($this->messageLogged), function($msg) use ($to, $subject){
                $msg->to($to)->subject($subject);
            });
        }
        return true;
    }


    /**
     * 生成错误表单
     * @param $data
     * @return string
     */
    protected function createFormData($data) {
        $content = "<tr><td style='width: 50%;border:1px solid black;'>Level</td><td style='width: 50%;border:1px solid black;'>{$data['level']}</td></tr>";
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>Message</td><td style='width: 50%;border:1px solid black;'>{$data['message']}</td></tr>";
        foreach ($data['context'] as $key => $item) {
            $content .= "<tr><td style='width: 50%;border:1px solid black;'>Content-{$key}</td><td style='width: 50%;border:1px solid black;'>". (is_string($item) ? $item : json_encode($item, 25)) ."</td></tr>";
        }
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>Create Time</td><td style='width: 50%;border:1px solid black;'>". date("Y-m-d H:i:s") ."</td></tr>";

        $html = "<html><body style='width: 100%;'><table style='width: 100%;border:1px solid black;text-align: center;' cellspacing='0' cellpadding='0'>{$content}</table></body></html>";
        return $html;
    }
}
